const jwt = require('jsonwebtoken');

// JWT认证中间件
const authMiddleware = (req, res, next) => {
  // 跳过认证的路径
  const publicPaths = ['/api/public', '/health', '/api/auth/login'];
  if (publicPaths.some(path => req.path.startsWith(path))) {
    return next();
  }

  // 从请求头中获取JWT令牌
  const authHeader = req.headers.authorization;
  if (!authHeader || !authHeader.startsWith('Bearer ')) {
    return res.status(401).json({ error: 'Unauthorized: No token provided' });
  }

  const token = authHeader.split(' ')[1];

  try {
    // 验证JWT令牌
    const decoded = jwt.verify(token, process.env.JWT_SECRET);
    req.user = decoded;
    next();
  } catch (error) {
    if (error.name === 'TokenExpiredError') {
      return res.status(401).json({ error: 'Unauthorized: Token expired' });
    }
    return res.status(401).json({ error: 'Unauthorized: Invalid token' });
  }
};

// 验证JWT令牌的函数
function verifyToken(token) {
  try {
    return jwt.verify(token, process.env.JWT_SECRET);
  } catch (error) {
    return null;
  }
}

module.exports = {
  authMiddleware,
  verifyToken
};